package com.jn.zhinongbao.adapter;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.supportingagriculturaltreasures.bean.News;

import java.io.File;

public class NewsDetailActivity extends AppCompatActivity {

    private TextView tvTitle, tvAuthor, tvTime, tvCategory, tvViewCount;
    private ImageView ivImage;
    private WebView webView;
    
    private News news;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);

        initViews();
        getNewsData();
        setupWebView();
        displayNews();
    }

    private void initViews() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("文章详情");
        }

        tvTitle = findViewById(R.id.tv_title);
        tvAuthor = findViewById(R.id.tv_author);
        tvTime = findViewById(R.id.tv_time);
        tvCategory = findViewById(R.id.tv_category);
        tvViewCount = findViewById(R.id.tv_view_count);
        ivImage = findViewById(R.id.iv_image);
        webView = findViewById(R.id.web_view);
    }

    private void getNewsData() {
        Intent intent = getIntent();
        news = intent.getParcelableExtra("news");
        if (news == null) {
            finish();
            return;
        }
    }

    private void setupWebView() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setDisplayZoomControls(false);
        
        // 设置WebView客户端
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });
    }

    private void displayNews() {
        if (news == null) return;

        // 显示基本信息
        tvTitle.setText(news.getTitle());
        tvAuthor.setText("作者：" + news.getAuthor());
        tvTime.setText(news.getCreateTime());
        tvCategory.setText(news.getCategory());
        tvViewCount.setText(String.valueOf(news.getViewCount()));

        // 处理图片
        Log.d("NewsDetail", "Image URL: " + news.getImageUrl());
        if (news.getImageUrl() != null && !news.getImageUrl().isEmpty()) {
            try {
                File imageFile = new File(news.getImageUrl());
                Log.d("NewsDetail", "Image file exists: " + imageFile.exists());
                Log.d("NewsDetail", "Image file path: " + imageFile.getAbsolutePath());
                
                if (imageFile.exists()) {
                    ivImage.setImageBitmap(BitmapFactory.decodeFile(news.getImageUrl()));
                    ivImage.setVisibility(View.VISIBLE);
                    Log.d("NewsDetail", "Image loaded successfully");
                } else {
                    // 如果文件不存在，显示默认图片
                    Log.d("NewsDetail", "Image file not found, showing default");
                    ivImage.setImageResource(android.R.drawable.ic_menu_gallery);
                    ivImage.setVisibility(View.VISIBLE);
                }
            } catch (Exception e) {
                Log.e("NewsDetail", "Error loading image", e);
                e.printStackTrace();
                // 发生异常时也显示默认图片
                ivImage.setImageResource(android.R.drawable.ic_menu_gallery);
                ivImage.setVisibility(View.VISIBLE);
            }
        } else {
            Log.d("NewsDetail", "No image URL provided");
            // 没有图片URL时也显示一个占位图
            ivImage.setImageResource(android.R.drawable.ic_menu_gallery);
            ivImage.setVisibility(View.VISIBLE);
        }

        // 在WebView中显示富文本内容
        String htmlContent = buildHtmlContent(news.getContent());
        webView.loadDataWithBaseURL(null, htmlContent, "text/html", "UTF-8", null);
    }

    private String buildHtmlContent(String content) {
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>");
        html.append("<html>");
        html.append("<head>");
        html.append("<meta charset='UTF-8'>");
        html.append("<meta name='viewport' content='width=device-width, initial-scale=1.0'>");
        html.append("<style>");
        html.append("body { font-family: Arial, sans-serif; line-height: 1.6; margin: 0; padding: 16px; background-color: #f5f5f5; }");
        html.append("p { margin: 0 0 16px 0; color: #333; font-size: 16px; }");
        html.append("br { margin: 8px 0; }");
        html.append("img { max-width: 100%; height: auto; border-radius: 8px; margin: 16px 0; }");
        html.append("h1, h2, h3 { color: #2E7D32; margin: 24px 0 16px 0; }");
        html.append("ul, ol { padding-left: 20px; }");
        html.append("li { margin: 8px 0; }");
        html.append("blockquote { background-color: #e8f5e8; border-left: 4px solid #4CAF50; margin: 16px 0; padding: 16px; border-radius: 4px; }");
        html.append("code { background-color: #f4f4f4; padding: 2px 4px; border-radius: 3px; font-family: monospace; }");
        html.append("</style>");
        html.append("</head>");
        html.append("<body>");
        
        // 如果内容已经是HTML格式，直接使用，否则进行简单的格式化
        if (content.contains("<html>") || content.contains("<body>")) {
            // 提取body内容
            if (content.contains("<body>") && content.contains("</body>")) {
                int startIndex = content.indexOf("<body>") + 6;
                int endIndex = content.indexOf("</body>");
                content = content.substring(startIndex, endIndex);
            }
            html.append(content);
        } else {
            // 简单的文本格式化
            html.append("<p>").append(content.replace("\n", "</p><p>")).append("</p>");
        }
        
        html.append("</body>");
        html.append("</html>");
        
        return html.toString();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }
} 